package com.rabbit.mq.service;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.UUID;

/**
 * 包含事务 ---- 能力有限，没有调通，网上看不到资源，都标注说不常用----------就没人用。。。
 */
@Service
public class RabbitTransactionPublisher implements RabbitTemplate.ReturnCallback {
    @Resource(name = "rabbitTransactedTemplate")
    private RabbitTemplate rabbitTransactedTemplate;

    @PostConstruct
    public void init() {
        // 将信道设置为事务模式
        rabbitTransactedTemplate.setReturnCallback(this);
        rabbitTransactedTemplate.setChannelTransacted(true);
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("事务 " + message + " 发送失败");
    }

    /**
     * @param exchange
     * @param routing
     * @param message
     * @return
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "rabbitTransactionManager")
    public String publish(String exchange, String routing, String message) {

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTransactedTemplate.convertAndSend(exchange, routing, message, correlationData);
        return message;
    }

    /**
     * @param routing
     * @param message
     * @return
     */
    public String publish(String routing, String message) {

        return this.publish("", routing, message);
    }
}